<?php
/*ACTIONS:
	login: When the user is trying to log in
	register: When the user wants to register

*/
startSession();
require 'util.php';

if(isset($_POST['action'])){
	$action = $_POST['action'];
	unset($_POST['action']);
	switch($action){

		case "login":
			$id = $_POST['id'];
			$pw = $_POST['pw'];
			login($id, $pw, $pdo);
			break;

		case "register":
			$userInfoArray = buildUserInfoArray($_POST);
			registerUser($userInfoArray, $pdo);
			break;
		case "logout":
			logout();
			break;
		case "usercheck":
			$user = $_POST['user'];
			userRegistered($user);
			break;
		case "emailcheck":
			$email = $_POST['email'];
			emailRegistered($email);
			break;
		case "completeRegistration":
			completeRegistration($_POST, $_FILES, $pdo);
			break;
		case "editProfile":
			editProfile($_POST, $_FILES, $pdo);
			break;
		default: 
			goToUrl($GLOBALS['loginPageUrl']);
			break;

	}
	
}else{
	goToUrl($GLOBALS['loginPageUrl']);
}

function editProfile($post, $files, $pdo){
	//print_r($files);
	$params = array(
		":first_name"=>$post['firstName'],
		":second_name"=>$post['secondName'],
		":first_lastname"=>$post['firstLastname'],
		":second_lastname"=>$post['secondLastname'],
		":postcode"=>$post['postcode'],
		":address"=>$post['address'],
		":gender_fk"=>$post['gender'],
		":date_of_birth"=>$post['dateOfBirth']
		);
	$paramsWhere = array(
			":user_fk"=>getLoggedInUser()
		);
	$response;
	$error;
	$responseMessage;
	if(executeUpdate("user_info", $params, $paramsWhere, $pdo) == 1){
		$error = false;
		$responseMessage = "all ok";
		
	}else{
		$error = true;
		$responseMessage = "There was a problem with your request. Please log in and try again.";
	}

	$response = array(
		"error" => $error,
		"responseMessage"=>$responseMessage
		);
	echo getJSON($response);
}
/*function processUserPictures($files){
	$dir = createDirectory("img/profiles/"+getLoggedInUser());
	$filePaths = moveFiles($files, $dir);
	if($filePaths && !empty($filePaths)){
		//print_r($filePaths);
		$params = array();
		if(isset($filePaths["primaryImage"])){
			$params[':first_image_url'] = $filePaths["primaryImage"];
		}
		if(isset($filePaths["secondaryImage"])){
			$params[':second_image_url'] = $filePaths["secondaryImage"];
		}
		$paramsWhere = array(
			":user_fk"=>getLoggedInUser()
			);
		return executeUpdate("user_info", $params, $paramsWhere, getPdo());
	}
	return true;
}*/
function completeRegistration($post, $files, $pdo){
	//print_r($files);
	$params = array(
		":user_fk"=>getLoggedInUser(),
		":first_name"=>$post['firstName'],
		":second_name"=>$post['secondName'],
		":first_lastname"=>$post['firstLastname'],
		":second_lastname"=>$post['secondLastname'],
		":postcode"=>$post['postcode'],
		":address"=>$post['address'],
		":gender_fk"=>$post['gender'],
		":date_of_birth"=>$post['dateOfBirth']
		);
	$response;
	$error;
	$responseMessage;
	$insertResponse = executeInsert("user_info", $params, $pdo);
	if($insertResponse != -1){
		
		$error = false;
		$responseMessage = "all ok";
		$dir = createDirectory("img/profiles/"+getLoggedInUser());

	}else{
		$error = true;
		$responseMessage = "There was a problem with your request. Please log in and try again.";
	}

	$response = array(
		"error" => $error,
		"responseMessage"=>$responseMessage
		);
	echo getJSON($response);
	
}
function login($id, $pw, $pdo){
	$parameters = array();
	$parameters[':id'] = htmlentities($id, ENT_QUOTES);
	$query = "SELECT * FROM user WHERE user.id= :id LIMIT 1";
	$result = getResultArray($query, $pdo, $parameters);
	$error = "ok"; //"ok" All ok, "login" Login info is wrong, "activation" not activated
	$errMessage = "";
	$allok = true;
	//print_r($result);
	if(!empty($result)){
		$result = $result[0];
		$salt = $result['salt'];
		if(crypt($result['pw'], "$".$salt."$") == crypt($pw, "$".$salt."$")){
			if(!$result['activated'] == 1){
				$error = "activation";
			}
		}else{
			$error = "login";
		}
	}else{
		$error = "login";
	}
	switch ($error) {
		case 'login':
			$allok = false;
			$errMessage = "Your login information is wrong. Please try again";
			break;
		case 'activation':
			$allok = false;
			$email = $result['email'];
			$errMessage = "account not activated. We have already sent an email to $email with the activation link.";
			break;
		default:
			$allok = true;
			break;
	}
	$error = false;
	$errorMessage = "";
	if($allok){
		doLogIn($result['pk']);
		$error = false;
		$errorMessage = "All ok";
	}else{
		$error = true;
		$errorMessage = $errMessage;
	}
	$responseArray = array(
		"error"=>$error,
		"response"=>$errorMessage
		);
	echo getJSON($responseArray);
}
function registerUser($userInfoArray, $pdo){
	$responseMessage;
	$error;

	$params = array(
		":id" => $userInfoArray["id"]
		);
	$pk;
	if(registerExists("user", $params, $GLOBALS['pdo']))
	{
		$error = true;
		$responseMessage = "Couldn't register the new user. The user already exists";
	}
	else
	{
		$params =array(
			":id"=>$userInfoArray["id"],
		 	":pw"=>$userInfoArray["pw"],
		 	":email"=>$userInfoArray["email"],
		 	":salt"=>generateRandomString(4),
		 	":activated"=>0
		 );
		$random_hash = md5(uniqid(rand(), true));
		$dt = new DateTime();
		$dt->add(new DateInterval('P7D'));
		//executeInsert("user", $params, $pdo);
		$pk = executeInsert("user", $params, $pdo);

		if($pk != "error"){
			$params = array(
				":user_fk"=>$pk,
				":key_pk"=>$random_hash,
				":expiration_date"=>date("Y-m-d H:i:s", $dt->getTimestamp())
				);
			if(executeInsert("registration_link", $params, $pdo) != "error"){
				$email = $userInfoArray['email'];
				$userName = $userInfoArray['id'];
				sendConfirmationLink($email, $random_hash, $userName);
			}
			$error = false;
			$responseMessage = "A confirmation email has been sent to $email. Please remember it expires in 7 days.";

		}
		else
		{
			$error = false;
			$responseMessage = "Couldn't register the new user. Please try again.";
		}
	}
	sendResponse($error, $responseMessage);
}

function sendResponse($error, $message){
	$response = array(
		"error"=> $error,
		"response"=>$message
		);
	echo getJSON($response);
}
function sendConfirmationLink($email, $random_hash, $userName){
	$to      = $email;
	$subject = 'Account Activation';
	$message = 'Thank you for joining us. Please click on the link below to activate your account:';
	$message .= "http://quizzie404.heliohost.org/test/activateAccount.php?h=$random_hash";
	$headers = 'From: webmaster@example.com' . "\r\n" .
   'Reply-To: webmaster@example.com' . "\r\n" .
   'X-Mailer: PHP/' . phpversion();
	mail($to, $subject, $message, $headers);
}
function buildUserInfoArray($post){
	$userInfoArray = Array();
	$userInfoArray['id'] = $post['id'];
	$userInfoArray['pw'] = $post['pw'];
	$userInfoArray['email'] = $post['email'];
	return $userInfoArray;
}

function startSession(){
	session_start();
}

function userRegistered($user, $pdo){
	$userExists = registerExists("user", array(":user" => $user), $pdo);
	if($userExists){
		echo "yes";
	}else{
		echo "no";
	}
}

function emailRegistered($email, $pdo){
	$emailExists = registerExists("user", array(":email" => $email), $pdo);
	if($emailExists){
		echo "yes";
	}else{
		echo "no";
	}
}



//https://github.com/panique/php-login-one-file/blob/master/index.php
?>
